package com.letianpai.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.letianpai.common.client.CommonTool;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2014/9/29.
 */
public class DataBaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_FILENAME = CommonTool.PROJECT_NAME;//数据库名
    private static String SD_FILE = CommonTool.DATABASE_PATH + "/" + DATABASE_FILENAME;
    private static String MOBILE_HONE_FILE = CommonTool.SHJI_PATH + "/" + DATABASE_FILENAME;
    private static DataBaseHelper dbInstance = null;
    private static String DATA_FILE = existSDcard() ? SD_FILE : MOBILE_HONE_FILE;
    private static SQLiteDatabase sqLiteDatabase = null;
    private Context context;
    private static int VERSION = 1000;

    /**
     * 显示调用父类的方法
     *
     * @param context
     */
    public DataBaseHelper(Context context) {
        //context上下文       name数据库名称      factory游标工厂   version数据库文件的版本号
        super(context, DATABASE_FILENAME, null, VERSION);
        //如果数据库被创建 那么数据库文件会被保存在当前应用所在的<包>/databases
        this.context = context;
    }

    /**
     * 单例模式 返回实例
     *
     * @param context
     * @return
     */
    public synchronized static DataBaseHelper getInstance(Context context) {
        if (dbInstance == null) {
            dbInstance = new DataBaseHelper(context);
        }
        return dbInstance;
    }

    public DataBaseHelper(Context context, String name, int version) {
        this(context, name, null, version);
    }

    public DataBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        this.context = context;
        this.VERSION = version;
    }

    public void close() {
        if (sqLiteDatabase != null) {
            sqLiteDatabase.close();
        }
    }


    /**
     * 删除数据库
     *
     * @param context
     * @return
     */
    public boolean deleteDatabase(Context context) {
        return context.deleteDatabase(DATA_FILE);
    }

    /**
     * 删除指定记录
     */
    public int delete(String tableName, String whereClause) {
        return sqLiteDatabase.delete(tableName, whereClause, null);
    }

    public void exec(String sql) {
        sqLiteDatabase.execSQL(sql);
    }

    /**
     * 添加记录*
     */
    public long insert(String tableName, ContentValues cv) {
        long id = sqLiteDatabase.insert(tableName, null, cv);
        return id;
    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
    }

    //该函数是在第一次创建的时候执行，实际上是第一次得到SQLiteDatabase对象的时候才会调用这个方法
    @Override
    public void onCreate(SQLiteDatabase db) {
        // db.execSQL("");
        List<String> sql_list = new ArrayList<String>();
        sql_list.add("CREATE TABLE picture_info(id text,pic_path text,pic_name text,pic_type text,pic_md5 text);");
        try {
            for (String sql : sql_list) {
                // 调用insert方法，就可以将数据插入到数据库当中   第一个参数:表名称
                // 第二个参数：SQl不允许一个空列，如果ContentValues是空的，那么这一列被明确的指明为NULL值
                // 第三个参数：ContentValues对象
                db.execSQL(sql);
            }
            db.setTransactionSuccessful();
            db.endTransaction();
        } catch (Exception e) {
        }
    }

    /**
     * 查询*
     */
    public Cursor read(String sql) {
        Cursor cur = sqLiteDatabase.rawQuery(sql, null);
        return cur;
    }

    public Cursor readOne(String sql) {
        Cursor cur = sqLiteDatabase.rawQuery(sql + " limit 1 offset 0", null);
        return cur;
    }

    /**
     * 判断某张表是否存在
     *
     * @param tableName 表名
     * @return
     */
    public boolean tableIsExist(String tableName) {
        boolean result = false;
        if (tableName == null) {
            return false;
        }
        Cursor cursor = null;
        try {
            String sql = "select count(*) as c from Sqlite_master  where type ='table' and name ='"
                    + tableName.trim() + "' ";
            cursor = sqLiteDatabase.rawQuery(sql, null);
            if (cursor.moveToNext()) {
                int count = cursor.getInt(0);
                if (count > 0) {
                    result = true;
                }
            }

        } catch (Exception e) {
        } finally {
            if (null != cursor) {
                cursor.close();
                cursor = null;
            }
        }
        return result;
    }

    /**
     * 更新记录
     *
     * @param tableName   表名
     * @param cv          值
     * @param whereClause 条件字段
     * @param whereClause 条件参数
     * @return
     */
    public int update(String tableName, ContentValues cv, String whereClause) {
        return sqLiteDatabase.update(tableName, cv, whereClause, null);
    }

    public interface DataType {
        public final String DATETIME = "DATETIME";
        public final String IMAGE = "IMAGE";
        public final String INT = "INT";
        public final String INTEGER = "INTEGER";
        public final String TEXT = "TEXT";
        public final String VARCHAR = "VARCHAR";
    }

    /**
     * 当数据库文件的版本号发生改变时调用
     */
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    }

    public void closeAll(Cursor cursor, SQLiteDatabase sqliteDatabase, DataBaseHelper helper) {
        try {
            if (cursor != null) {
                cursor.close();
            }
            if (sqliteDatabase != null) {
                sqliteDatabase.close();
            }
            if (helper != null) {
                helper = null;
            }
        } catch (Exception e) {
        }
    }

    //判断SD卡是否存在
    private static boolean existSDcard() {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            return true;
        } else
            return false;
    }
}
